package com.xinyi.basic.base.activity

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Printer
import android.view.ViewGroup
import android.view.Window
import androidx.appcompat.app.AppCompatActivity
import com.xinyi.basic.thread.ThreadHandler
import com.xinyi.basic.utils.LogUtil
import java.lang.ref.WeakReference

/**
 * @author 新一
 * @date 2023/3/28 19:41
 * @description Activity基类，鉴于handler在日常开发中使用频率较高，因此在基类中封装了handler的使用
 */
abstract class BaseActivity : AppCompatActivity() {

    // HandlerCallback 对象，用于处理接收到的消息
    // A handlerCallback object that processes received messages
    private var mHandlerCallback: HandlerCallback? = null

    // mThreadHandler 对象，用于在后台线程执行任务并处理消息
    // An mThreadHandler object used to perform tasks and handle messages on a background thread
    private var mThreadHandler: ThreadHandler? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mHandlerCallback = HandlerCallback(this)
        mThreadHandler = ThreadHandler.createHandler(mHandlerCallback, MessagePrinter())

        dealIntent(intent)

        setContentView()
        initViews()
        initParams()
        initListeners()
    }

    open fun setContentView() {
        setContentView(initLayoutId())
    }

    /**
     * 初始化布局文件
     */
    protected abstract fun initLayoutId(): Int

    /**
     * 处理 Intent
     */
    protected open fun dealIntent(mIntent: Intent?) {}

    /**
     * 初始化视图
     */
    protected open fun initViews() {}

    /**
     * 初始化参数
     */
    protected open fun initParams() {}

    /**
     * 初始化监听器
     */
    protected open fun initListeners() {}

    /**
     * 用于打印 Handler 消息队列中的消息的实现类
     *
     * Implementation class for printing messages in the Handler message queue.
     */
    class MessagePrinter : Printer {

        /**
         * 打印消息
         *
         * Prints a message.
         *
         * @param x 要打印的消息字符串
         *          The message string to be printed.
         */
        override fun println(x: String?) {
            LogUtil.d("Handler Message Queue（Handler消息队列）(Looper)：$x")
        }
    }

    /**
     * 线程处理器消息的回调实现类
     *
     * Callback implementation class for thread handler messages.
     *
     * @param mThreadHandler 对 BaseThreadHandlerHook 的弱引用
     *                       Weak reference to BaseThreadHandlerHook
     */
    class HandlerCallback(mThreadHandler: BaseActivity) : Handler.Callback {

        private val mWeakThreadHandler: WeakReference<BaseActivity> = WeakReference(mThreadHandler)

        /**
         * 处理接收到的消息
         *
         * Handles the received message.
         *
         * @param msg 接收到的消息对象
         *            Received message object
         *
         * @return 如果消息已处理则返回 true，如果消息未处理则返回 false
         *         If the message has been processed, return true; If the message has not been processed, return false.
         */
        override fun handleMessage(msg: Message): Boolean {
            LogUtil.i("Handler消息：$msg")

            val mActivity = mWeakThreadHandler.get() ?: return false
            mActivity.handleMessage(msg)

            return false
        }

        fun clear() {
            mWeakThreadHandler.clear()
        }
    }

    /**
     * 处理消息回调的方法。子类需要实现这个方法来处理接收到的消息。
     *
     * Callback method for handling messages. Subclasses need to implement this method to handle received messages.
     *
     * @param msg 接收到的消息对象
     *            Received message object
     */
    protected open fun handleMessage(msg: Message) { }

    override fun onDestroy() {
        try {
            mThreadHandler?.quit()
            mHandlerCallback?.clear()
            mThreadHandler = null
            mHandlerCallback = null
        } catch (ex: Exception) {
            ex.printStackTrace()
        }
        super.onDestroy()
    }

    /**
     * 在主线程上运行任务
     *
     * Runs a task on the main thread.
     *
     * @param task 要执行的任务
     *             The task to be executed.
     */
    fun runOnUiThreadRunnable(task: Runnable?) {
        task ?: return
        mThreadHandler?.runOnUiThread(task)
    }

    /**
     * 在主线程上运行任务
     *
     * Runs a task on the main thread with delay.
     *
     * @param task 要执行的任务
     *             The task to be executed.
     * @param duration 延迟执行的时间（毫秒）
     *                 The time (in milliseconds) to delay execution. Default value is 0, which means execute immediately.
     */
    fun runOnUiThread(task: Runnable?, duration: Long) {
        task ?: return
        mThreadHandler?.runOnUiThread(task, duration)
    }

    /**
     * 从主线程中移除指定的任务
     *
     * Removes a specified task from the main thread.
     *
     * @param task 要移除的任务
     *             The task to be removed.
     */
    fun removeFromUiThread(task: Runnable?) {
        task ?: return
        mThreadHandler?.removeFromUiThread(task)
    }

    /**
     * 将任务添加到队列中，在工作线程中执行
     *
     * Adds a task to the queue and executes it on the worker thread.
     *
     * @param task 要添加到队列中的任务
     *             The task to be added to the queue.
     */
    @Synchronized
    fun queueEvent(task: Runnable?) {
        task ?: return
        mThreadHandler?.queueEvent(task)
    }

    /**
     * 将任务添加到队列中，在工作线程中执行
     *
     * Adds a task to the queue and executes it on the worker thread.
     *
     * @param task 要添加到队列中的任务
     *             The task to be added to the queue.
     * @param delayMillis 延迟执行的时间（毫秒）
     *                    The time (in milliseconds) to delay execution. Default value is 0, which means execute immediately.
     */
    @Synchronized
    fun queueEvent(task: Runnable?, delayMillis: Long = 0) {
        task ?: return
        mThreadHandler?.queueEvent(task, delayMillis)
    }

    /**
     * 从队列中移除指定的任务
     *
     * Removes a specified task from the queue.
     *
     * @param task 要移除的任务
     *             The task to be removed.
     */
    @Synchronized
    protected fun removeEvent(task: Runnable?) {
        task ?: return
        mThreadHandler?.removeEvent(task)
    }

    /**
     * 移除队列中的所有任务和消息
     *
     * Removes all tasks and messages from the queue.
     */
    @Synchronized
    protected fun removeCallbacksAndMessages() {
        mThreadHandler?.removeCallbacksAndMessages()
    }

    /**
     * 发送消息到工作线程的消息队列中
     *
     * Sends a message to the worker thread message queue.
     *
     * @param msg 要发送的消息对象
     *            The message object to be sent.
     */
    @Synchronized
    protected fun sendMessage(msg: Message) {
        mThreadHandler?.sendThreadMessageDelayed(msg, 0)
    }

    /**
     * 发送线程消息/延迟
     *
     * Sends a message to the worker thread message queue with optional delay.
     *
     * @param msg 要发送的消息对象
     *            The message object to be sent.
     * @param delayMillis 延迟执行的时间（毫秒）
     *                    The time (in milliseconds) to delay execution. Default value is 0, which means execute immediately.
     */
    @Synchronized
    protected fun sendThreadMessageDelayed(msg: Message, delayMillis: Long = 0) {
        mThreadHandler?.sendThreadMessageDelayed(msg, delayMillis)
    }

    /**
     * 和 setContentView 对应的方法
     */
    fun getContentView(): ViewGroup {
        return findViewById(Window.ID_ANDROID_CONTENT)
    }
}